package com.nami.ucenter.controller.midddleware.mq.consumer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONUtil;
import com.nami.ucenter.facade.timeout.request.UserTimeoutCmd;
import com.nami.gate.external.basic.constants.UpTopicConst;
import com.nami.ucenter.facade.timeout.ConnectedTimeoutFacade;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
@RocketMQMessageListener(topic = UpTopicConst.CONNECT_TIMEOUT_TOPIC,
    consumerGroup = UpTopicConst.CONNECT_TIMEOUT_TOPIC,
    consumeMode = ConsumeMode.CONCURRENTLY)
public class ConnectTimeoutConsumer implements RocketMQListener<String> {

    private final ConnectedTimeoutFacade timeoutFacade;

    @Override
    public void onMessage(String message) {
        try {
            log.info("[connect-consumer] begin. message:{}", message);
            TimeInterval timer = DateUtil.timer();
            UserTimeoutCmd cmd = parseTimeoutMessage(message);
            if (cmd == null) {
                log.warn("[connect-consumer] message is empty");
                return;
            }
            timeoutFacade.execute(cmd);
        } catch (Exception var3) {
            var3.printStackTrace();
            log.error("timeout error:", var3);
        }

    }

    private static @Nullable UserTimeoutCmd parseTimeoutMessage(String message) {
        if (StringUtils.isBlank(message)) {
            log.warn("[connect-consumer] message is empty");
            return null;
        }
        UserTimeoutCmd body = JSONUtil.toBean(message, UserTimeoutCmd.class);
        return body;
    }


}
